from sanic import Sanic
import aiomysql
import aioredis
from sanic import response
import asyncio
from product_api import SpecificMethoD

SpecificMethod = SpecificMethoD()
import json

from . import bp_product



@bp_product.route("/product_info")
async def product_type_info(request):

    if not request.method == 'GET':
    
        return response.json({
                'status': -1,
                'errorCode': 1,
                'errorMsg':f"请求方式error,request.method:{request.method}",
                'resultBody':None
            })

    info = request.args

    product_type = info.get('product_type')

    if not product_type:

        return response.json({
                'status': -1,
                'errorCode': 8,
                'errorMsg':f"缺少参数product_type:{product_type}",
                'resultBody':None
            })

    product_info = await SpecificMethod.get_str(product_type)

    if product_info != None:
        #'从redis中取'
        product_info = json.loads(product_info)

    elif product_info == None:
        '从数据库中取'
        product_info = await SpecificMethod.select_info(sql="select * from product_info where product_type=%s",args=product_type)
        # product_info = {'product_info':i for i in product_info}
        # print(product_info)
        product_info = str(product_info)
        product_info_json = json.dumps(product_info)
        await SpecificMethod.set_str(product_type, product_info_json)

    return response.json({
                'status': 1,
                'errorCode': None,
                'errorMsg':None,
                'resultBody':{product_type:product_info}
            })

@bp_product.route("/product")
async def product_all_info(request):

    if not request.method == 'GET':
    
        return response.json({
                'status': -1,
                'errorCode': 1,
                'errorMsg':f"请求方式error,request.method:{request.method}",
                'resultBody':None
            })

    product_all = await SpecificMethod.get_str('product_all')

    if product_all != None:
        #'从redis中取'
        product_all = json.loads(product_all)

    elif product_all == None:
        '从数据库中取'
        product_all = await SpecificMethod.select_info(sql="select * from product")
        product_all = str(product_all)
        if product_all == None:
            return response.json({
                                    'status': 1,
                                    'errorCode': None,
                                    'errorMsg': None,
                                    'resultBody':product_all
                                })

        product_all_json = json.dumps(product_all)
        await SpecificMethod.set_str('product_all', product_all_json)

    return response.json({
                'status': 1,
                'errorCode': None,
                'errorMsg':None,
                'resultBody':product_all
            })

@bp_product.route("/product_id",methods=['POST'])
async def product_type_info(request):

    if not request.method == 'POST':
    
        return response.json({
                'status': -1,
                'errorCode': 1,
                'errorMsg':f"请求方式error,request.method:{request.method}",
                'resultBody':None
            })

    product_id = request.form.get('product_id')
    
    product = await SpecificMethod.select_info(sql="select * from product where id=%s;",args=product_id)

    if product == None:
        return response.json({
                                'status': 1,
                                'errorCode': None,
                                'errorMsg':None,
                                'resultBody':'暂无'
                            })
        
    return response.json({
                            'status': 1,
                            'errorCode': None,
                            'errorMsg':None,
                            'resultBody':{product_id:product}
                        })

@bp_product.route("/add_product",methods=['POST',])

async def insert_product_work(request):

    if not request.method == 'POST':

        return response.json({
                'status': -1,
                'errorCode': 1,
                'errorMsg':f"请求方式error,request.method:{request.method}",
                'resultBody':None
            })

    info = request.form

    product_name = info.get("product_name")
    product_image = request.files.get("product_image")
    product_price = info.get("product_price")
    

    if not all([product_name,product_image,product_price]):

        return response.json({
                'status': -1,
                'errorCode': 9,
                'errorMsg':f"缺少参数product_name:{product_name},product_image:{product_image},product_price:{product_price}",
                'resultBody':None
            })

    all_product =await SpecificMethod.select_info(sql="select product_name from product")

    if {'product_name': product_name} in all_product:
        
        return response.json({
                'status': -1,
                'errorCode': 10,
                'errorMsg':f"添加商品失败请检查product_name{product_name}是否已创建",
                'resultBody':None
            })

    with open("static/product_img/{}.jpg".format(product_name), 'wb') as f:

        info = f.write(product_image.body)

        if not info:

            return response.json({
                'status': -1,
                'errorCode': 21,
                'errorMsg':f"添加商品失败请检查product_image:{product_image}格式",
                'resultBody':None
            })

    product_image_url = "/static/product_img/{}".format(product_name)

    work = await SpecificMethod.insert_info(sql="insert into product(product_name,product_image,product_price)values(%s,%s,%s);",args=(product_name,product_image_url,product_price))

    if not work:

        return response.json({
                'status': -1,
                'errorCode': 11,
                'errorMsg':f"添加商品失败请检查product_name:{product_name},product_image:{product_image},product_price:{product_price}格式",
                'resultBody':None
            })

    await SpecificMethod.delete_str('product_all')

    return response.json({
                'status': 1,
                'errorCode': None,
                'errorMsg':None,
                'resultBody':'添加商品成功'
            })
    
@bp_product.route("/delete_product",methods=['POST',])

async def delete_product_work(request):

    if not request.method == 'POST':

        return response.json({
                'status': -1,
                'errorCode': 1,
                'errorMsg':f"请求方式error,request.method:{request.method}",
                'resultBody':None
            })

    info = request.form

    product_name = info.get("product_name")

    if not product_name:

        return response.json({
                'status': -1,
                'errorCode': 12,
                'errorMsg':f"缺少参数product_name{product_name}",
                'resultBody':None
            })

    work = await SpecificMethod.insert_info(sql="DELETE FROM product WHERE product_name=%s",args=product_name)

    if not work:

        return response.json({
                'status': -1,
                'errorCode': 13,
                'errorMsg':f"删除商品失败请检查product_name{product_name}格式",
                'resultBody':None
            })

    await SpecificMethod.delete_str('product_all')

    return response.json({
                'status': 1,
                'errorCode': None,
                'errorMsg':None,
                'resultBody':'删除商品成功'
            })

@bp_product.route("/update_product",methods=['POST',])#无用
async def update_product_work(request):

    if not request.method == 'POST':

        return response.json({
                'status': -1,
                'errorCode': 1,
                'errorMsg':f"请求方式error,request.method:{request.method}",
                'resultBody':None
            })

    info = request.form

    old_product_name = info.get("old_product_name")
    new_product_name = info.get("new_product_name")
    product_image = request.files.get("product_image")
    product_price = info.get("product_price")

    if not all([old_product_name,new_product_name,product_image,product_price]):

        return response.json({
                'status': -1,
                'errorCode': 14,
                'errorMsg':f"缺少参数old_product_name:{old_product_name},new_product_name:{new_product_name},product_image:{product_image},product_price:{product_price}",
                'resultBody':None
            })

    with open("./static/file_img/{}".format(old_product_name), 'wb') as f:

        info = f.write(product_image)

        if not info:

            return response.json({
                'status': -1,
                'errorCode': 11,
                'errorMsg':f"添加商品失败请检查product_image:{product_image}格式",
                'resultBody':None
            })

    product_image_url = "/static/product_img/{}".format(new_product_name)

    work = await SpecificMethod.insert_info(sql="UPDATE product SET product_name=%s,product_image=%s,product_price=%s WHERE product_name=%s",args=(new_product_name,product_image_url,product_price,old_product_name))

    if not work:

        return response.json({
                'status': -1,
                'errorCode': 15,
                'errorMsg':f"更新商品失败请检查old_product_name:{old_product_name},new_product_name:{new_product_name},product_image:{product_image},product_price:{product_price}格式",
                'resultBody':None
            })

    await SpecificMethod.delete_str('product_all')

    return response.json({
                'status': 1,
                'errorCode': None,
                'errorMsg':None,
                'resultBody':'更新商品成功',
            })